package com.tianyuan.lims.dms.controller.app;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.tianyuan.lims.common.config.paragetter.BasePageRequest;
import com.tianyuan.lims.common.constant.BaseConstant;
import com.tianyuan.lims.dms.entity.ZbtProductWty;
import com.tianyuan.lims.erp.admin.entity.AdminUser;
import com.tianyuan.lims.utils.BaseUtil;
import io.github.yedaxia.apidocs.ApiDoc;
import com.tianyuan.lims.utils.R;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ZbtProductWtyController extends Controller {


    /**
     * 附件上传
     */
//    public String upload(UploadFile file) throws InterruptedException {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
//        String formatTime = sdf.format(new Date());
//        String fileName = file.getFileName();
//        String last = fileName.substring(fileName.lastIndexOf("."));
//        String newName = formatTime + last;
//        File newFile = new File(BaseConstant.UPLOAD_PATH+ "/upload/file/" + newName);
//        file.getFile().renameTo(newFile);
//        Thread.sleep(20);
//        return  "/upload/file/" + newName;
//    }

    // 200KB的字节数
    //private static final long MAX_SIZE = 200 * 1024;
    private static final long MAX_SIZE = 50 * 1024;

    public String  upload(UploadFile file) throws InterruptedException, IOException {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
//        String formatTime = sdf.format(new Date());
//        String fileName = file.getFileName();
//        String last = fileName.substring(fileName.lastIndexOf("."));
//        String newName = formatTime + last;
//        String filePath = BaseConstant.UPLOAD_PATH + "/upload/file/" + newName;
//
//        // 先保存原始文件
//        File originalFile = new File(filePath);
//        file.getFile().renameTo(originalFile);
//
//        // 检查文件大小，如果超过200KB则进行压缩
//        if (file.getFile().length() > MAX_SIZE) {
//            compressFile(originalFile, filePath, last);
//        }
//
//        Thread.sleep(20);
//        return "/upload/file/" + newName;

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
//        String formatTime = sdf.format(new Date());
//        String fileName = file.getFileName();
//        String last = fileName.substring(fileName.lastIndexOf("."));
//        String newName = formatTime + last;
//        String filePath = BaseConstant.UPLOAD_PATH + "/upload/file/" + newName;
//
//// 确保目录存在
//        File targetDir = new File(BaseConstant.UPLOAD_PATH + "/upload/file/");
//        if (!targetDir.exists()) {
//            targetDir.mkdirs(); // 创建目录（包括必要的父目录）
//        }
//
//        File originalFile = new File(filePath);
//
//// 使用更可靠的文件复制方式替代renameTo
//        try (InputStream in = new FileInputStream(file.getFile());
//             OutputStream out = new FileOutputStream(originalFile)) {
//
//            byte[] buffer = new byte[1024];
//            int length;
//            while ((length = in.read(buffer)) > 0) {
//                out.write(buffer, 0, length);
//            }
//        } catch (IOException e) {
//            throw new RuntimeException("文件保存失败: " + e.getMessage(), e);
//        }
//
//// 检查文件是否存在且可读取
//        if (!originalFile.exists() || !originalFile.canRead()) {
//            throw new FileNotFoundException("保存后的文件不存在或无法读取: " + filePath);
//        }
//
//// 检查文件大小，如果超过200KB则进行压缩
//        if (originalFile.length() > MAX_SIZE) {
//            compressFile(originalFile, filePath, last);
//        }
//
//        Thread.sleep(20);
//        return "/upload/file/" + newName;
//    }
//
//    // 压缩文件的方法（这里以图片为例）
//    private void compressFile(File originalFile, String filePath, String ext) throws IOException {
//        // 只处理图片文件
//        if (ext.matches("(?i)\\.(jpg|jpeg|png|gif)")) {
//            BufferedImage image = ImageIO.read(originalFile);
//
//            // 计算压缩比例
//            float scale = (float) Math.sqrt(MAX_SIZE / (double) originalFile.length());
//            int newWidth = (int) (image.getWidth() * scale);
//            int newHeight = (int) (image.getHeight() * scale);
//
//            // 创建压缩后的图片
//            BufferedImage compressedImage = new BufferedImage(
//                    newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
//            compressedImage.getGraphics().drawImage(
//                    image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH),
//                    0, 0, null);
//
//            // 覆盖原始文件
//            ImageIO.write(compressedImage, ext.substring(1), new File(filePath));
//        } else {
//            // 对于非图片文件，可以根据需求实现其他压缩逻辑
//            throw new UnsupportedOperationException("不支持的文件类型压缩: " + ext);
//        }
//    }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String formatTime = sdf.format(new Date());
        String fileName = file.getFileName();
        String last = fileName.substring(fileName.lastIndexOf("."));
        String newName = formatTime + last;
        String filePath = BaseConstant.UPLOAD_PATH + "/upload/file/" + newName;
// 创建临时文件路径，用于保存压缩前的原始文件
        String tempFilePath = filePath + ".temp";

// 确保目录存在
        File targetDir = new File(BaseConstant.UPLOAD_PATH + "/upload/file/");
        if (!targetDir.exists()) {
            targetDir.mkdirs(); // 创建目录（包括必要的父目录）
        }

        File tempFile = new File(tempFilePath);
        File originalFile = new File(filePath);

// 先将文件保存到临时位置
        try (InputStream in = new FileInputStream(file.getFile());
             OutputStream out = new FileOutputStream(tempFile)) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败: " + e.getMessage(), e);
        }

// 检查临时文件是否存在且可读取
        if (!tempFile.exists() || !tempFile.canRead()) {
            throw new FileNotFoundException("保存后的临时文件不存在或无法读取: " + tempFilePath);
        }

// 检查文件大小，如果超过200KB则进行压缩
        if (tempFile.length() > MAX_SIZE) {
            // 压缩临时文件到目标位置
            compressFile(tempFile, filePath, last);
            // 压缩完成后删除临时文件
            if (!tempFile.delete()) {
                // 可以选择记录日志，提示临时文件删除失败
                System.err.println("警告: 无法删除临时文件: " + tempFilePath);
            }
        } else {
            // 如果不需要压缩，直接将临时文件重命名为目标文件
            if (!tempFile.renameTo(originalFile)) {
                // 重命名失败时使用复制方式
                try (InputStream in = new FileInputStream(tempFile);
                     OutputStream out = new FileOutputStream(originalFile)) {

                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = in.read(buffer)) > 0) {
                        out.write(buffer, 0, length);
                    }
                }
                // 复制完成后删除临时文件
                if (!tempFile.delete()) {
                    System.err.println("警告: 无法删除临时文件: " + tempFilePath);
                }
            }
        }
//        if(originalFile.exists()){
//            originalFile.delete();
//        }


        Thread.sleep(20);
        return "/upload/file/" + newName;
    }

    // 压缩文件的方法（这里以图片为例）
    private void compressFile(File tempFile, String filePath, String ext) throws IOException {
        // 只处理图片文件
        if (ext.matches("(?i)\\.(jpg|jpeg|png|gif)")) {
            BufferedImage image = ImageIO.read(tempFile);

            // 计算压缩比例
            float scale = (float) Math.sqrt(MAX_SIZE / (double) tempFile.length());
            int newWidth = (int) (image.getWidth() * scale);
            int newHeight = (int) (image.getHeight() * scale);

            // 创建压缩后的图片
            BufferedImage compressedImage = new BufferedImage(
                    newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            compressedImage.getGraphics().drawImage(
                    image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH),
                    0, 0, null);

            // 保存压缩后的文件到目标路径
            ImageIO.write(compressedImage, ext.substring(1), new File(filePath));
        } else {
            // 对于非图片文件，可以根据需求实现其他压缩逻辑
            throw new UnsupportedOperationException("不支持的文件类型压缩: " + ext);
        }
    }

    @ApiDoc(url = "/zbtProductWty/save", method = "post")
    public void save() {
        try{
            String file1 = "";
            String file2 = "";
            String file3 = "";
            List<UploadFile> fileList = getFiles();
            for (int i = 0; i < fileList.size(); i++) {
                UploadFile uploadFile = fileList.get(i);
                String fileName = upload(uploadFile);
                if(i == 0){
                    file1 = fileName;
                }
                if(i == 1){
                    file2 = fileName;
                }
                if(i == 2){
                    file3 = fileName;
                }
                uploadFile.getFile().delete();
            }

            Long userId = BaseUtil.getUserId();
            if (userId == null) {
                renderJson(R.error("请先登录！"));
            }
            //String data = getRawData();
            //ZbtProductWty model = JSON.parseObject(data, ZbtProductWty.class);
            String username = getPara("username");
            String mobile = getPara("mobile");
            String productname = getPara("productname");
            String wtyendStr = getPara("wtyend");
            String remark = getPara("remark");

            String jineStr = getPara("jine");
            String zhuangtaiStr = getPara("zhuangtai");

            ZbtProductWty model = new ZbtProductWty();
            model.setUsername(username);
            model.setMobile(mobile);
            model.setProductname(productname);
            model.setWtystart(new Date());
            model.setWtyend(DateUtil.parse(wtyendStr));
            model.setMerchantid(userId.intValue());

            model.setRemark(remark);

            model.setJine(jineStr);
            model.setZhuangtai(zhuangtaiStr);

            model.setFile1(file1);
            model.setFile2(file2);
            model.setFile3(file3);


            //ZbtProductWty model = getModel(ZbtProductWty.class);
            if (model.save()) {
                renderJson(R.ok("保存成功"));
            } else {
                renderJson(R.ok("保存失败"));
            }
        }catch (Exception e){
            e.printStackTrace();
            renderJson(R.error("系统错误！"));
        }
    }
    @ApiDoc(url = "/zbtProductWty/get", method = "post")
    public void get() {
        int id = getParaToInt();
        ZbtProductWty model = ZbtProductWty.dao.findById(id);
        if (model != null) {
            renderJson(R.ok().put("data", model));
        } else {
            renderJson(R.ok("未找到记录"));
        }
    }
    @ApiDoc(url = "/zbtProductWty/update", method = "post")
    public void update() {
        ZbtProductWty model = getModel(ZbtProductWty.class);
        if (model.update()) {
            renderJson(R.ok("更新成功"));
        } else {
            renderJson(R.ok("更新失败"));
        }
    }
    @ApiDoc(url = "/zbtProductWty/delete", method = "post")
    public void delete() {
        int id = getParaToInt();
        if (ZbtProductWty.dao.deleteById(id)) {
            renderJson(R.ok("删除成功"));
        } else {
            renderJson(R.ok("删除失败"));
        }
    }


    @ApiDoc(url = "/zbtProductWty/list", method = "post")
    public void list(BasePageRequest<ZbtProductWty> basePageRequest) {
        String mobile = getPara("mobile");
        String warrantyDate = getPara("warrantyDate");
        String zhuangtai = getPara("zhuangtai");


        Long userId = BaseUtil.getUserId();
        if (userId == null) {
            renderJson(R.error("请先登录！"));
        }

        String riqiSql = " ";
        if(StringUtils.isNotBlank(warrantyDate)){
            riqiSql = " and wtystart = '" + warrantyDate+ "' ";
        }

        if(warrantyDate.equals("全部日期")){
            riqiSql = "  ";
        }

        String ztSql = " ";
        if(StringUtils.isNotBlank(zhuangtai)){
            ztSql = " and zhuangtai = '" + zhuangtai+ "' ";
        }
        if(zhuangtai.equals("全部状态")){
            ztSql = "  ";
        }



        List<Record> recordList = new ArrayList<>();
        if(StringUtils.isNotEmpty(mobile)){
            recordList = Db.find("select * from zbt_product_wty where merchantid = "+userId+" and mobile = '" + mobile + "'" +
                    riqiSql + ztSql + "  order by id desc");
        }else{
            recordList = Db.find("select * from zbt_product_wty where merchantid = "+userId+" " +
                    riqiSql + ztSql + " order by id desc  limit 20");

            if((zhuangtai.equals("全部状态") || zhuangtai.equals("正常")) && warrantyDate.equals("全部日期")){
                recordList = Db.find("select * from zbt_product_wty where merchantid = "+userId+" " +
                        riqiSql + ztSql + " order by id desc  limit 10");
            }
        }

        renderJson(R.ok().put("data", recordList));
    }


    @ApiDoc(url = "/zbtProductWty/list1", method = "post")
    public void list1(BasePageRequest<ZbtProductWty> basePageRequest) {
        String mobile = getPara("mobile");
        List<Record> recordList = new ArrayList<>();
        if(StringUtils.isNotEmpty(mobile)){
            //recordList = Db.find("select * from zbt_product_wty where  mobile = '" + mobile + "'");
            recordList = Db.find("select prod.*,usr.realname from zbt_product_wty prod, crm_admin_user usr\n" +
                    "            where prod.merchantid = usr.user_id " +
                    "and  prod.mobile = '" + mobile + "'" +
                    //"and  prod.zhuangtai in ('正常','欠款')" +
                    " order by prod.id desc");
        }
        renderJson(R.ok().put("data", recordList));
    }



    @ApiDoc(url = "/zbtProductWty/updateStatus", method = "post")
    public void updateStatus() {
        try{
            Long userId = BaseUtil.getUserId();
            if (userId == null) {
                renderJson(R.error("请先登录！"));
            }
            Integer id = getParaToInt("id");
            String zhuangtaiStr = getPara("zhuangtai");
            ZbtProductWty model = new ZbtProductWty();
            model.setId(id);
            model.setZhuangtai(zhuangtaiStr);
            if (model.update()) {
                renderJson(R.ok("保存成功"));
            } else {
                renderJson(R.ok("保存失败"));
            }
        }catch (Exception e){
            e.printStackTrace();
            renderJson(R.error("系统错误！"));
        }
    }

}
